﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Domain.Extensions
{
	using System.IO;
	using System.Web.Mvc;
	using Falcon.Core.Extensions;

	public static class UserAlbumPhotoExtension
	{
		// private constants
		private const string ThumbFormat = "{0}_{1}_{2}{3}";

		/// <summary>
		/// Gets the thumbnail for the user album photo.
		/// </summary>
		/// <param name="helper">The helper.</param>
		/// <param name="photo">The photo.</param>
		/// <param name="w">The w.</param>
		/// <param name="h">The h.</param>
		/// <returns></returns>
		public static string Thumbnail(this UrlHelper helper, UserAlbumPhoto photo, int w, int h)
		{
			var route = helper.Route(Routes.UserAlbumPhotoDetail, new
			{
				id = photo.Id,
				slug = photo.Slug
			});

			var name = ThumbFormat.Fmt(
				Path.GetFileNameWithoutExtension(photo.Attachment.FileDiskName),
				w,
				h,
				Path.GetExtension(photo.Attachment.FileDiskName)
			);

			var path = Path.Combine(photo.Attachment.FilePath, name);
			var file = new FileInfo(path.AsPath());

			if (!file.Exists)
			{
				var image = helper.RouteUrl(Routes.AttachmentImage, new
				{
					id = photo.Attachment.Id,
					width = w,
					height = h
				});

				return route.Image(image, false, new { alt = photo.Title, title = photo.Title });
			}

			return route.Image(path.AsRoot(), false, new { alt = photo.Title, title = photo.Title });
		}
	}
}